package top.kiterunner.learning.concurrency_test;

import java.util.concurrent.TimeUnit;

/**
 * AdorynZhao in Tencent-UESTC.
 * Source Code Created on 2017/7/6.
 */
public class ThreadDemo10 {

    public volatile int count = 0;

    public void method1() {
        long before = System.currentTimeMillis();
        synchronized (this) {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            count++;

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        long after = System.currentTimeMillis();
        System.out.println(Thread.currentThread().getName() + " => Time Difference = " + (after - before));
    }

    public void method2() {
        long before = System.currentTimeMillis();
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        synchronized (this) {
            count++;
        }

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long after = System.currentTimeMillis();
        System.out.println(Thread.currentThread().getName() + " => Time Difference = " + (after - before));
    }

    public static void main(String[] args) {
        ThreadDemo10 t10 = new ThreadDemo10();

        long before = System.currentTimeMillis();

        // 对比过程：
        // 过程1：thread1 - method1 / thread2 - method2
        // 过程2：thread1 - method1 / thread2 - method1
        // 过程3：thread1 - method2 / thread2 - method2
        // 同时分析为什么会出现这种情况。。
        Thread thread1 = new Thread(t10::method1, "Thread1");
        Thread thread2 = new Thread(t10::method2, "Thread2");

        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long after = System.currentTimeMillis();
        System.out.println(Thread.currentThread().getName() + " => Time Difference = " + (after - before));
    }
}
